package com.dpp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class UploadUtil {

    public String upload(String basePath,MultipartFile img){
        try {
            String originalFilename = img.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString().replace("-","") + extension;

            //创建一个目录对象
            File dir = new File(basePath);
            //没有目录则创建
            if(!dir.exists()){
                dir.mkdirs();
            }

            String filePath = basePath+objectName;
            img.transferTo(new File(filePath));
            return objectName;
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
            return null;
        }
    }
}
